<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Traits;

use Hyperf\Context\ApplicationContext;
use Hyperf\Redis\Redis;

trait RandomTraits
{
    /**
     * 生成递增订单号.
     * @return string
     */
    public static function generateIncOrderId(int $num = 5)
    {
        // 假设已经建立了Redis连接并存储在$redis变量中
        $redisKey = 'order_id_increment';
        $redis = ApplicationContext::getContainer()->get(Redis::class);
        // 获取当前ID
        $id = $redis->get($redisKey);
        if ($id == null || $id > pow(10, $num) - 1) {
            $id = 1;
        } else {
            ++$id;
        }
        // 设置新的ID到Redis
        $redis->set($redisKey, $id);
        return /* date('Ymd') . */ $num . sprintf('%0' . $num . 'd', $id) . sprintf('%02d', rand(0, 99));
    }
}
